#!/bin/bash

set -e

port=8080

# Spin a test server in the background
node ./script/server $port &>/dev/null &
server_pid=$!
trap "kill $server_pid" INT EXIT

make sauce_connect/bin/sc
sauce_ready="${TMPDIR:-/tmp}/sauce-ready.$$"
sauce_connect/bin/sc -u "$SAUCE_USERNAME" -k "$SAUCE_ACCESS_KEY" \
  -i "$TRAVIS_JOB_NUMBER" -l sauce_connect.log -f "$sauce_ready" &>/dev/null &
sauce_pid=$!
trap "kill $sauce_pid" INT EXIT

sauce_waited=0
while [ ! -f "$sauce_ready" ]; do
  if [ "$sauce_waited" -gt 60000 ]; then
    echo "sauce_connect failed to start within 60 seconds" >&2
    exit 1
  fi
  sleep .01
  sauce_waited=$((sauce_waited + 10))
done
echo "sauce_connect started within $sauce_waited ms"
rm -f "$sauce_ready"

job="$(./script/saucelabs-api --raw "js-tests" <<JSON
  { "public": "public",
    "build": "$TRAVIS_BUILD_NUMBER",
    "tags": ["$TRAVIS_PULL_REQUEST", "$TRAVIS_BRANCH"],
    "tunnel-identifier": "$TRAVIS_JOB_NUMBER",
    "platforms": [["$SAUCE_PLATFORM", "$SAUCE_BROWSER", "$SAUCE_VERSION"]],
    "url": "http://localhost:$port/",
    "framework": "mocha"
  }
JSON
)"

while sleep 5; do
  result=$(./script/saucelabs-api "js-tests/status" <<<"$job")
  if grep -q '.status: test error' <<<"$result"; then
    echo
    echo "$result" >&2
    exit 1
  fi
  grep -q "^completed: true" <<<"$result" && break
  echo -n "."
done

echo

awk '
  /result\.tests:/ { tests+=$(NF) }
  /result\.passes:/ { passes+=$(NF) }
  /result\.pending:/ { pending+=$(NF) }
  /result\.failures:/ { failures+=$(NF) }
  /\.url:/ { print $(NF) }
  END {
    printf "%d passed, %d pending, %d failures\n", passes, pending, failures
    if (failures > 0 || tests != passes + pending || tests == 0) exit 1
  }
' <<<"$result"
